package com.dage.salesflow.kit;

import com.alibaba.excel.util.ListUtils;
import com.jfinal.kit.StrKit;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class DateTimeKit {
	public static List<SimpleDateFormat> formatList;

	static {
		formatList = ListUtils.newArrayListWithExpectedSize(4);
		formatList.add(new SimpleDateFormat("yyyy-M-d"));
		formatList.add(new SimpleDateFormat("yyyy年M月d日"));
		formatList.add(new SimpleDateFormat("yyyy-M-d H:m:s"));
		formatList.add(new SimpleDateFormat("yyyy-MM-dd"));
		formatList.add(new SimpleDateFormat("yyyy年MM月dd日"));
		formatList.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}

	/**
	 * 解析日期字符串，尝试所有可能的格式
	 */
	public static Date toDate(String dateStr) throws ParseException {
		if (StrKit.isBlank(dateStr)) {
			return null;
		}
		dateStr = dateStr.trim();
		try {
			return parseDate(dateStr, 0);
		} catch (ParseException e) {
			dateStr = dateStr.replace(".", "-");
			dateStr = dateStr.replace("/", "-");
			return parseDate(dateStr, 0);
		}
	}

	private static Date parseDate(String dateStr, int i) throws ParseException {
		try {
			return formatList.get(i).parse(dateStr);
		} catch (ParseException e) {
			if (i < formatList.size() - 1) {
				return parseDate(dateStr, ++i);
			} else {
				throw e;
			}
		}
	}
}
